import UserCodeCaptcha from '@/components/UserCodeCaptcha';
import { updateUserPassword } from '@/services/user';
import { LOGIN_PATH } from '@/constant';
import { ResponseCode } from '@/utils/request';
import { LockOutlined, SendOutlined } from '@ant-design/icons';
import { ProFormText } from '@ant-design/pro-components';
import { Link } from '@umijs/max';
import { Button, Form, message, Space } from 'antd';
import React, { useState } from 'react';
import { history } from '@umijs/max';
import VerifyMessage from '../components/VerifyMessage';

type SubmitParams = Parameters<typeof updateUserPassword>['0'];

const Login: React.FC = () => {
  const [errorMsg, setErrorMsg] = useState<string>();
  const [formInstance] = Form.useForm();

  const handleSubmit = async () => {
    let values: SubmitParams;
    try {
      values = await formInstance.validateFields();
    } catch (error: any) {
      return;
    }
    try {
      // 注册
      const { code, message: msg } = await updateUserPassword({ ...values });
      switch (code) {
        case ResponseCode.Success: {
          setErrorMsg(undefined);
          message.success(msg || '修改成功');
          // 跳转登入
          history.push(LOGIN_PATH);
        }
        case ResponseCode.Fail: {
          setErrorMsg(msg);
          throw new Error(msg);
        }
      }
    } catch (error: any) {
      console.log('Verify => Forget => handleSubmit', '请求失败');
    }
  };

  return (
    <Form form={formInstance}>
      {errorMsg && <VerifyMessage content={errorMsg} />}

      <ProFormText
        name="email"
        fieldProps={{
          size: 'large',
          prefix: <SendOutlined className="prefix-icon" />,
        }}
        placeholder={'邮箱: '}
        rules={[
          {
            required: true,
            message: '请输入邮箱！',
          },
        ]}
      />

      <UserCodeCaptcha formInstance={formInstance} />

      <ProFormText.Password
        name="password"
        fieldProps={{
          size: 'large',
          prefix: <LockOutlined className="prefix-icon" />,
          autoComplete: 'current-password',
        }}
        placeholder={'密码: '}
        rules={[
          {
            required: true,
            message: '请输入密码！',
          },
        ]}
      />

      <Button
        type="primary"
        style={{ width: '100%', marginTop: '12px' }}
        size="large"
        onClick={handleSubmit}
      >
        找回密码
      </Button>

      <Space
        style={{ marginTop: 24, width: '100%', flexDirection: 'row-reverse' }}
      >
        <Link to="/verify/login">返回登入</Link>
      </Space>
    </Form>
  );
};

export default Login;
